package utilities.tcpserver;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import utilities.tcpserver.events.event;

public class unmanaged 
	extends utilities.events.dispatcher
	implements Runnable
{
	private boolean running;
	private InetSocketAddress endpoint;
	
	protected ServerSocket socket;
	
	public unmanaged(InetSocketAddress endpoint)
	{
		this.endpoint = endpoint;
		
		try {
			socket = new ServerSocket();
			socket.bind(endpoint);
		} catch(IOException error) {}
	}
	
	public unmanaged(int port)
	{
		this(new InetSocketAddress(port));
	}
	
	public void run()
	{
		running = true;
		while(running == true)
		{
			try {
				Socket client = socket.accept();
				utilities.tcpserver.session session = new utilities.tcpserver.session(client);
				new Thread(session).start();
				
				fireEvent(new event(this, session, event.EventCodes.SESSION_OPENED));
			} catch(IOException error) {}
		}
	}
	
	public void start()
	{
		new Thread(this).start();
	}
	
	public void stop()
	{
		running = false;
		
		try {
			socket.close();
		} catch(IOException error) {}
	}

	public InetSocketAddress getEndpoint() 
	{
		return endpoint;
	}
}
